package com.prothink.threadproject.interceptor;

import com.prothink.threadproject.util.JWTToken;
import com.sun.org.apache.bcel.internal.generic.RET;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JWTTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object object){
        System.out.println("requestMethod"+ request.getMethod() +"requestURL"+ request.getRequestURI());
        if (request.getMethod().equals("OPTIONS")){
            return true;
        }
        String token = request.getHeader("Authorization");
        System.out.println("Token" + token);
        //1.判断有没有Token,拒绝用户访问
        if (StringUtils.isEmpty(token)){
            response.setStatus(401);
            return false;
        }
        //2.解析Token,如果解析报错,也说明Token有问题
        if (token != null && token.startsWith("Bearer ")) {//是否是指定的前缀
            // 提取 "Bearer " 后面的 token 部分
            token = token.substring(7);
            System.out.println("Token: " + token);
        } else {
            System.out.println("Authorization 标头无效。");
        }
        String subject = "";
        try{
            subject = JWTToken.parseToken(token);
//            //数据库查询这个账号,看存不存在这个用户,如果存在就说明正常的token ,如果不存在,就说明这个Token有问题
//            System.out.println("subject" + subject);
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }

        System.out.println("subject" + subject);
        return true;
    }
}
